package com.hd.trans.widgets.views.floatwindow.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import com.hd.trans.widgets.views.floatwindow.component.FloatWindow;


public abstract class BaseFloatWindow<T extends ViewDataBinding> {

    protected T mDataBinding;
    protected Context mContext;

    private final FloatWindow mFloatWindow;

    private FloatWindow.OnOrientationChangedListener onOrientationChangedListener;

    private boolean mCreated = false;

    public BaseFloatWindow(@NonNull Context context){
        mContext = context;
        mFloatWindow = createFloatWindow(context);

        mFloatWindow.setOnOrientationChangedListener(isLandscape -> {
            this.onOrientationChanged(isLandscape);
            if (onOrientationChangedListener != null) {
                onOrientationChangedListener.onOrientationChanged(isLandscape);
            }
        });

    }

    private void onCreate() {
        if (!mCreated) {
            mCreated = true;
            initView(mDataBinding);
        }
    }

    protected abstract int getLayoutId();

    protected abstract void initView(@NonNull T dataBinding);

    protected FloatWindow getMFloatWindow() {
        return mFloatWindow;
    }

    @NonNull
    protected abstract FloatWindow createFloatWindow(@NonNull Context context);

    @NonNull
    protected View getContentView(){
        if (mDataBinding == null){
            View view = LayoutInflater.from(mContext).inflate(getLayoutId(),null,false);
            mDataBinding = DataBindingUtil.bind(view);
            if (mDataBinding == null){
                throw new IllegalArgumentException("View is not a binding layout");
            }
        }
        return mDataBinding.getRoot();
    }

    public void setOnOrientationChangedListener(FloatWindow.OnOrientationChangedListener listener) {
        this.onOrientationChangedListener = listener;
    }

    /**
     * 屏幕方向改变
     * @param isLandscape 是否横屏
     */
    protected void onOrientationChanged(boolean isLandscape){

    }

    public boolean isShowing(){
        return mFloatWindow.isShowing();
    }

    public boolean isLandscape(){
        return mFloatWindow.isLandscape();
    }

    @CallSuper
    public void show(){
        mFloatWindow.show();
        onCreate();
    }

    public void hidden(){
        mFloatWindow.hidden();
    }

    public void remove(){
        mFloatWindow.remove();
    }

}
